<template>
  <div class="page-order">
    <div class="search-bar">
      <el-form
        :inline="true"
        :model="dataForm"
        @submit.prevent
        @keyup.enter="onSearch(true)"
      >
        <div class="input-row">
          <el-form-item :label="$t('order.number') + '：'">
            <el-input
              v-model="dataForm.orderNumber"
              :placeholder="$t('order.number')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('order.orderType') + '：'">
            <el-select
              v-model="dataForm.orderType"
              clearable
              :placeholder="$t('order.pleaseSelectOrderType')"
            >
              <el-option
                v-for="item in orderType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('group.orderStatus') + '：'">
            <el-select
              v-model="status"
              clearable
              :placeholder="$t('order.statusMsg')"
              @change="orderStatus"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.theRecipientSName') + '：'">
            <el-input
              v-model="dataForm.receiver"
              :placeholder="$t('order.pleaseEnRecipName')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('shop.contactTel') + '：'">
            <el-input
              v-model="dataForm.mobile"
              :placeholder="$t('order.pleaseEnterNumber')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('order.paymentMethod') + '：'">
            <el-select
              v-model="dataForm.payType"
              clearable
              :placeholder="$t('order.pleaseSePayt')"
            >
              <el-option
                v-for="item in payType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('order.afterSalesStatus') + '：'">
            <el-select
              v-model="dataForm.refundStatus"
              clearable
              :placeholder="$t('order.pleSelAfterSalesSta')"
            >
              <el-option
                v-for="item in refund"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.logisticsType') + '：'">
            <el-select
              v-model="dataForm.dvyType"
              clearable
              :placeholder="$t('order.pleSelTypeOfLog')"
            >
              <el-option
                v-for="item in dvyType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('station.stationName') + '：'">
            <el-input
              v-model="dataForm.stationName"
              :placeholder="$t('station.stationNames')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('order.createTime') + '：'">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="-"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
              :default-time="defaultTime"
            />
            <div
              style="margin-left: 20px"
              class="default-btn date-selection"
              @click="onSetDateRange(1)"
            >
              {{ $t('date.t') }}
            </div>
            <div
              class="default-btn date-selection"
              @click="onSetDateRange(2)"
            >
              {{ $t('date.y') }}
            </div>
            <div
              class="default-btn date-selection"
              @click="onSetDateRange(3)"
            >
              {{ $t('date.n') }}
            </div>
            <div
              class="default-btn date-selection"
              @click="onSetDateRange(4)"
            >
              {{ $t('m') }}
            </div>
          </el-form-item>
          <el-form-item style="margin-bottom: 20px">
            <div
              class="primary-btn default-btn"
              @click="onSearch(true)"
            >
              {{ $t('order.query') }}
            </div>
            <div
              class="default-btn"
              @click="onGetSoldExcel()"
            >
              {{ $t('formData.export') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch()"
            >
              {{ $t('crud.emptyBtn') }}
            </div>
            <div
              v-if="isAuth('order:order:exportunorder')"
              class="default-btn"
              @click="onUploadSpu"
            >
              {{ $t('order.BulkShipping') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main">
      <div class="content">
        <!-- 导航 -->
        <div :class="['status-nav', 'clearfix', showHeadScroll ? 'status-nav-bottom' : '']">
          <ul class="nav-list clearfix">
            <li
              :class="['nav-item', sts === 0 ? 'selected' : '']"
              data-sts="0"
              @click="onSelectNav($event)"
            >
              {{ $t('date.a') }}
            </li>
            <li
              :class="['nav-item', sts === 1 ? 'selected' : '']"
              data-sts="1"
              @click="onSelectNav($event)"
            >
              {{ $t('order.pendingPayment') }}
            </li>
            <li
              :class="['nav-item', sts === 2 ? 'selected' : '']"
              data-sts="2"
              @click="onSelectNav($event)"
            >
              {{ $t('order.toBeShipped') }}
            </li>
            <li
              :class="['nav-item', sts === 3 ? 'selected' : '']"
              data-sts="3"
              @click="onSelectNav($event)"
            >
              {{ $t('order.pendingReceipt') }}
            </li>
            <li
              :class="['nav-item', sts === 5 ? 'selected' : '']"
              data-sts="5"
              @click="onSelectNav($event)"
            >
              {{ $t('order.successfulTransaction') }}
            </li>
            <li
              :class="['nav-item', sts === 6 ? 'selected' : '']"
              data-sts="6"
              @click="onSelectNav($event)"
            >
              {{ $t('order.transactionFailed') }}
            </li>
            <li
              :class="['nav-item', sts === 7 ? 'selected' : '']"
              data-sts="7"
              @click="onSelectNav($event)"
            >
              {{ $t('group.waitGroup') }}
            </li>
          </ul>
        </div>

        <!-- 列标题 -->
        <div
          :class="['tit', showHeadScroll ? 'fixed-top' : '']"
          :style="{
            width: !showHeadScroll ? '100%' : sidebarFold ? 'calc(83.5% + 130px )' : '83.5%'
          }"
        >
          <el-row style="width: 100%">
            <el-col :span="7">
              <span class="item product">{{ $t('home.product') }}</span>
            </el-col>
            <el-col
              :span="3"
              class="transaction-price"
            >
              <span class="item">{{ $t('order.transaQuantity') }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t('order.actualPaymentAmount') }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t('order.paymentMethod') }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t('order.buyerConsignee') }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t('group.orderStatus') }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t('order.afterSalesStatus') }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t('publics.operating') }}</span>
            </el-col>
          </el-row>
        </div>

        <div
          v-for="order in dataList"
          :key="order.orderId"
          class="prod"
          style="margin-bottom: 15px"
        >
          <div class="prod-tit">
            <span>{{ $t('order.number') }}：{{ order.orderNumber }}</span>
            <span>{{ $t('order.createTime') }}：{{ order.createTime }}</span>
          </div>
          <div class="prod-cont">
            <el-row style="width: 100%">
              <el-col
                :span="10"
                style="height: 100%"
              >
                <div class="prod-item">
                  <div
                    v-for="orderItem in order.orderItems"
                    :key="orderItem.orderItemId"
                    class="items name"
                  >
                    <div class="prod-image">
                      <!-- ImgShow组件 -->
                      <ImgShow :src="orderItem.pic" />
                    </div>
                    <div class="prod-name">
                      <div class="prod-con">
                        <div class="prod-name-txt">
                          {{ orderItem.prodName }}
                        </div>
                        <div
                          v-if="order.orderType === 1 || order.orderType === 2"
                          class="order-status"
                        >
                          {{
                            order.orderType === 1
                              ? $t('order.groupPurchaseOrder')
                              : order.orderType === 2
                                ? $t('order.spikeOrder')
                                : ''
                          }}
                        </div>
                        <div
                          v-if="
                            !orderItem.returnMoneySts ||
                              orderItem.returnMoneySts < 0 ||
                              orderItem.returnMoneySts > 5
                          "
                          class="order-status"
                        >
                          {{
                            orderItem.status === 0 && order.status === 2
                              ? $t('order.pendingReceipt')
                              : [
                                '',
                                $t('order.pendingPayment'),
                                $t('order.toBeShipped'),
                                $t('order.pendingReceipt'),
                                '',
                                $t('order.successfulTransaction'),
                                $t('order.transactionFailed'),
                                $t('group.waitGroup')
                              ][order.status]
                          }}
                        </div>
                        <div
                          v-else
                          class="order-status"
                        >
                          {{
                            [
                              '',
                              $t('order.buyerApplication'),
                              $t('order.sellerAccepts'),
                              $t('order.selShipment'),
                              $t('order.sellerReceipt'),
                              $t('order.refundSuccessfully')
                            ][orderItem.returnMoneySts]
                          }}
                        </div>
                        <div
                          v-if="order.dvyType === 2 || order.dvyType === 4"
                          class="order-status"
                        >
                          {{
                            order.dvyType === 2
                              ? $t('order.selfMention')
                              : order.dvyType === 4
                                ? $t('order.sameCityDelivery')
                                : ''
                          }}
                        </div>
                        <div
                          v-if="order.preSaleTime !== null"
                          class="order-status"
                        >
                          {{ $t('order.EstimatedDeliveryTime') }}{{ preSellTimeShowHandler(order.preSaleTime) }}
                        </div>
                      </div>
                    </div>
                    <div class="prod-price">
                      <span>{{ orderItem.price.toFixed(2) }}</span>
                      <span>{{ orderItem.prodCount }}{{ $t('marketing.item') }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span class="totalprice">{{ order.actualTotal.toFixed(2) }}</span>
                    <span
                      v-if="order.score && order.score > 0"
                      class="totalprice"
                    >+ {{ order.score }}{{ $t('order.integral') }}</span>
                    <div v-if="order.freightAmount">
                      （{{ $t('order.includingFreight') }}：{{ order.freightAmount.toFixed(2) }}）
                    </div>
                    <div>
                      {{ $t('order.total') }}{{ order.productNums }}{{ $t('marketing.item') }}
                    </div>
                    <div
                      v-if="order.status === 1"
                      class="default-btn text-btn"
                      @click="onEditAmount(order)"
                    >
                      {{ $t('order.modifyTheAmount') }}
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span v-if="order.payType === null || order.status === 1">{{
                      $t('order.unpaid')
                    }}</span>
                    <span v-else>{{
                      [
                        $t('order.pointsPayment'),
                        $t('order.wecProPay'),
                        $t('order.alipayPCPayment'),
                        $t('order.wechatScanCodePayment'),
                        $t('order.wechatH5Payment'),
                        $t('order.weclAccountPay'),
                        $t('order.alipayH5Payment'),
                        $t('order.alipayAPPPayment'),
                        $t('order.wechatAPPPayment'),
                        $t('order.balancePayment'),
                        $t('order.payPalPayment')
                      ][order.payType]
                    }}</span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div class="buyer-info">
                    <div class="buyer-name">
                      {{ order.receiverName }}
                    </div>
                    <div class="buyer-phone">
                      {{ order.receiverMobile }}
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span>
                    <span
                      v-if="order.status === 1"
                      type="danger"
                    >{{
                      $t('order.pendingPayment')
                    }}</span>
                    <span
                      v-else-if="order.status === 2"
                      type="danger"
                    >{{
                      $t('order.toBeShipped')
                    }}</span>
                    <span
                      v-else-if="order.status === 3"
                      type="danger"
                    >{{
                      $t('order.pendingReceipt')
                    }}</span>
                    <span
                      v-else-if="order.status === 7"
                      type="danger"
                    >{{
                      $t('group.waitGroup')
                    }}</span>
                    <span
                      v-else-if="order.status === 5"
                      type="danger"
                    >{{
                      $t('order.successfulTransaction')
                    }}</span>
                    <span v-else-if="order.status === 6">{{ $t('order.transactionFailed') }}</span>
                  </span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span
                    v-if="order.refundStatus === 1"
                    type="danger"
                  >{{
                    $t('order.requestARefund')
                  }}</span>
                  <span
                    v-else-if="order.refundStatus === 2"
                    type="danger"
                  >{{
                    $t('order.refundsuccessfully')
                  }}</span>
                  <span
                    v-else-if="order.refundStatus === 3"
                    type="danger"
                  >{{
                    $t('order.partialRefundSucc')
                  }}</span>
                  <span
                    v-else-if="order.refundStatus === 4"
                    type="danger"
                  >{{
                    $t('order.refundFailed')
                  }}</span>
                  <span
                    v-else
                    type="danger"
                  >{{ $t('order.noAfterSales') }}</span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div class="operate">
                    <div
                      v-if="isAuth('order:order:info')"
                      class="default-btn text-btn"
                      @click="onAddOrUpdate(order.orderNumber)"
                    >
                      {{ $t('order.seeDetails') }}
                    </div>
                    <div
                      class="default-btn text-btn operate-btn"
                      @click="onToImbox(order)"
                    >
                      {{ $t('order.contactBuyer') }}
                    </div>
                    <div
                      v-if="
                        order.status === 3 &&
                          (!order.refundStatus || order.refundStatus > 2) &&
                          order.isOnlineDelivery === 0
                      "
                      class="default-btn text-btn"
                      @click="onReviseLogistics(order.orderNumber)"
                    >
                      {{ $t('order.modifyLogistics') }}
                    </div>
                    <div
                      v-if="order.status === 2 && order.dvyType !== 2"
                      class="default-btn text-btn"
                      @click="onChangeOrder(order)"
                    >
                      {{ $t('order.delivery') }}
                    </div>
                    <div
                      v-if="order.status === 2 && order.dvyType === 2"
                      class="default-btn text-btn"
                      @click="onStationOrder(order)"
                    >
                      {{ $t('order.pickUp') }}
                    </div>
                    <div
                      v-if="order.refundStatus"
                      class="default-btn text-btn"
                      @click="onRefundRoute(order.orderNumber)"
                    >
                      {{ $t('order.refundInformation') }}
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div
          v-if="!dataList.length"
          class="empty"
        >
          {{ $t('order.noData') }}
        </div>
      </div>
    </div>
    <div class="el-pagination">
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="onGetDataList"
    />
    <order-station
      v-if="orderStationVisible"
      ref="orderStationRef"
      @refresh-order-station-data-list="onGetDataList"
    />
    <order-amount-update
      v-if="orderAmountUpdateVisible"
      ref="orderAmountUpdateRef"
      @refresh-order-amount-update="onMountUpdate"
    />

    <order-delivery-update
      v-if="devyVisible"
      ref="orderDeliveryUpdateRef"
      @refresh-order-amount-update="onGetDataList"
    />
    <el-dialog
      v-model="logVisible"
      :title="$t('order.changeLogisticsInfo')"
      :close-on-click-modal="false"
      width="50%"
      @close="onHandleDialogClose"
    >
      <!-- 修改 -->
      <div
        v-if="isReviseLog"
        class="revise-log"
      >
        <div class="change-logistics">
          <div class="warning">
            {{ $t('order.ifModifyTheLog') }}
          </div>
          <div class="log-list">
            <div
              v-for="(logItem, index) in logisticsInfo"
              :key="index"
              class="item"
            >
              <div class="i-tit">
                <div class="big">
                  {{ $t('order.package') }}{{ index + 1 }}
                </div>
                <div class="text">
                  {{ $t('order.total') }} {{ logItem.productNums }} {{ $t('marketing.item')
                  }}{{ $t('home.product') }}
                </div>
              </div>
              <el-form
                ref="logDataFormRef"
                :model="logDataForm"
                label-width="95px"
                @submit.prevent
                @keyup.enter="onLogDataFormSubmit()"
              >
                <div class="item-goods">
                  <div
                    ref="carouserRef"
                    class="goods-box"
                  >
                    <div
                      v-for="(orderItem,i) in logItem.orderItems"
                      :key="i"
                      class="item"
                    >
                      <div class="img">
                        <prod-pic
                          height="60"
                          width="60"
                          :pic="orderItem.pic"
                        />
                        <div class="number">
                          ×{{ orderItem.prodCount }}
                        </div>
                      </div>
                      <div class="name">
                        {{ orderItem.prodName }}
                      </div>
                    </div>
                  </div>
                </div>
                <el-form-item
                  :label="$t('order.delType') + '：'"
                  style="text-align: left"
                >
                  <el-radio-group
                    v-model="logItem.tempDeliveryType"
                    class="log-radio-group"
                  >
                    <el-radio
                      v-model="radio"
                      :label="1"
                      disabled
                    >
                      {{
                        $t('order.ordinaryExpress')
                      }}
                    </el-radio>
                    <el-radio
                      v-model="radio"
                      :label="3"
                      disabled
                    >
                      {{
                        $t('order.noNeedRequired')
                      }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <!--配送方式 线上 线下-->
                <el-form-item
                  v-if="logItem.tempDeliveryType === 1"
                  :label="$t('order.delType') + '：'"
                  style="text-align: left;"
                >
                  <el-radio-group v-model="logItem.deliveryType">
                    <el-radio
                      :label="0"
                      disabled
                    >
                      {{
                        $t("order.onlineDelivery")
                      }}
                    </el-radio>
                    <el-radio
                      :label="1"
                      disabled
                    >
                      {{
                        $t("order.selfDelivery")
                      }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <div
                  v-if="logItem.deliveryType !== 3 &&logItem.deliveryType !== 0"
                  class="info-int"
                >
                  <el-form-item
                    :label="$t('order.courierCompany') + '：'"
                    class="form-item"
                  >
                    <div
                      v-if="logVisible"
                      class="con"
                    >
                      <SelectLazy v-model="logItem.dvyId" />
                    </div>
                  </el-form-item>
                  <el-form-item
                    :label="$t('order.trackingNumber') + '：'"
                    class="form-item"
                  >
                    <el-input
                      v-model="logItem.dvyFlowId"
                      controls-position="right"
                      maxlength="20"
                      :min="0"
                      :class="['int-frame', errorNum === 1 ? 'errortip' : '']"
                    />
                  </el-form-item>
                </div>
                <div
                  v-if="logItem.deliveryType === 0"
                  class="info-int"
                >
                  <el-form-item
                    :label="$t('order.courierCompany') + '：'"
                    class="form-item"
                    style="text-align: left;"
                  >
                    <div
                      v-if="logVisible"
                      class="con"
                    >
                      {{ deliveryCompanyType[logItem.dvyId - 1]?.label }}
                    </div>
                  </el-form-item>
                  <el-form-item
                    :label="$t('order.trackingNumber') + '：'"
                    class="form-item"
                  >
                    {{ logItem.dvyFlowId }}
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </div>

      <!-- 确认 -->
      <div
        v-if="!isReviseLog"
        class="change-logistics"
      >
        <div class="warning">
          {{ $t('order.ifModifyTheLog') }}
        </div>
        <el-table
          class="log-info-table"
          :data="confirmList"
        >
          <el-table-column
            property="dvyIdName"
            :label="$t('order.packageName')"
            width="220"
            style="text-align: left"
          />
          <el-table-column
            property="productNums"
            :label="$t('order.amountOfGoods')"
            width="140"
          />
          <el-table-column
            property="delMethod"
            :label="$t('order.deliveryMethod')"
            width="140"
          />
          <el-table-column
            property="dvyName"
            :label="$t('order.logisticsCompany')"
            width="170"
          />
          <el-table-column
            property="dvyFlowId"
            :label="$t('order.trackingNumber')"
          />
        </el-table>
      </div>

      <template #footer>
        <div
          v-if="isReviseLog"
          class="dialog-footer"
        >
          <div
            class="default-btn"
            @click="logVisible = false"
          >
            {{ $t('crud.filter.cancelBtn') }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="onLogDataFormSubmit()"
          >
            {{ $t('order.save') }}
          </div>
        </div>
        <div
          v-if="!isReviseLog"
          class="dialog-footer"
        >
          <div
            class="default-btn"
            @click="onBackToRevise()"
          >
            {{ $t('order.backToModify') }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="onConfirmRevise()"
          >
            {{ $t('order.confirmTheChanges') }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- /修改物流弹窗 -->
    <order-upload
      v-if="uploadVisible"
      ref="spuUploadRef"
      :param="dataForm"
      @refresh-data-list1="onGetWaitingConsignmentExcel"
    />
  </div>
</template>

<script setup>
import OrderStation from './components/station.vue'
import AddOrUpdate from './add-or-update.vue'
import OrderAmountUpdate from './components/amount-update.vue'
import OrderDeliveryUpdate from './components/delivery-update.vue'
import OrderUpload from './components/upload.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils/index'
import moment from 'moment'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

const radio = ref('1')
const options = [
  {
    value: 1,
    label: $t('order.pendingPayment')
  },
  {
    value: 2,
    label: $t('order.toBeShipped')
  },
  {
    value: 3,
    label: $t('order.pendingReceipt')
  },
  {
    value: 5,
    label: $t('order.successfulTransaction')
  },
  {
    value: 6,
    label: $t('order.transactionFailed')
  },
  {
    value: 7,
    label: $t('group.waitGroup')
  }
]
const refund = [
  {
    value: 0,
    label: $t('order.noAfterSales')
  },
  {
    value: 1,
    label: $t('order.requestARefund')
  },
  {
    value: 2,
    label: $t('order.refundsuccessfully')
  },
  {
    value: 3,
    label: $t('order.partialRefundSucc')
  },
  {
    value: 4,
    label: $t('order.refundFailed')
  }
]
const dvyType = [
  {
    value: 1,
    label: $t('order.expressDelivery')
  },
  {
    value: 2,
    label: $t('order.selfMention')
  },
  {
    value: 3,
    label: $t('order.noNeedRequired')
  },
  {
    value: 4,
    label: $t('order.sameCityDelivery')
  }
]
const payType = [
  {
    value: -1,
    label: $t('admin.unpay')
  },
  {
    value: 0,
    label: $t('order.pointsPayment')
  },
  {
    value: 1,
    label: $t('admin.weChatPay')
  },
  {
    value: 2,
    label: $t('admin.aliPay')
  },
  {
    value: 3,
    label: $t('platform.balancePay')
  },
  {
    value: 4,
    label: $t('admin.payPal')
  }
]
const orderType = [
  {
    value: 0,
    label: $t('order.normalOrder')
  },
  {
    value: 1,
    label: $t('order.groupPurchaseOrder')
  },
  {
    value: 2,
    label: $t('order.spikeOrder')
  }
]
const deliveryCompanyType = [{
  value: 1,
  label: '顺丰速运'
}, {
  value: 2,
  label: '京东快递'
}, {
  value: 3,
  label: '圆通速递'
}, {
  value: 4,
  label: '韵达快递'
}, {
  value: 5,
  label: '中通快递'
}, {
  value: 6,
  label: '申通快递'
}, {
  value: 7,
  label: '百世快递'
}, {
  value: 8,
  label: 'EMS'
}]
const store = useCommonStore()
const sidebarFold = computed({
  get () {
    return store.sidebarFold
  },
  set (val) {
    store.updateSidebarFold(val)
  }
})
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
onActivated(() => {
  // 携带参数查询
  const query = store.query
  if (Object.keys(query).length > 0) {
    onGetDataList(page.value, query)
    query?.orderNumber && onAddOrUpdate(query.orderNumber)
  }
})
const sts = ref(0)
const status = ref(null)
onMounted(() => {
  // 首页跳转状态参数
  sts.value = +route.query.status || 0
  status.value = sts.value === 0 ? null : Number(sts.value)
  // 携带参数查询
  onGetDataList(page.value, route.query)
  route?.query?.orderNumber && onAddOrUpdate(route.query.orderNumber)
  // // 请求物流公司
  onGetLogisticsList()

  // // 监听页面滚动
  window.addEventListener('scroll', scrollToTop)
})

/**
 * 弹窗关闭事件
 */
const isReviseLog = ref(true) // 是否正在修改物流信息
const onHandleDialogClose = () => {
  isReviseLog.value = true
}
/**
 * 页面滚动事件
 */
const showHeadScroll = ref(false) // 修改物流相关
const scrollToTop = () => {
  const scrollTop =
    window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  showHeadScroll.value = scrollTop > 400
}

/**
 * 获取包裹物流信息
 */
const logVisible = ref(false)
const logisticsInfo = ref([]) // 包裹列表
const errorNum = ref(0)
const confirmList = ref([]) // 确认修改信息

const onReviseLogistics = orderNumber => {
  const packageName = $t('order.package')
  logVisible.value = !logVisible.value
  http({
    url: http.adornUrl('/order/delivery/getOrderDeliveries/' + orderNumber),
    method: 'put'
  }).then(({ data }) => {
    logisticsInfo.value = data
    logisticsInfo.value.forEach((el, index) => {
      el.tempDeliveryType = el.deliveryType === 1 || el.deliveryType === 0 ? 1 : el.deliveryType
      el.newDvyFlowId = el.dvyFlowId
      el.newDvyId = el.dvyId
      el.dvyIdName = packageName + Number(index + 1)
      // 修改弹窗
      confirmList.value = [] // 清空确认列表
    })
  })
  errorNum.value = 0
}

/**
 * 请求物流公司列表
 */
const logDataForm = ref({
  dvyId: '', // 当前物流公司id
  dvyFlowId: '', // 物流单号
  dvyNames: [] // 物流公司列表
})
const onGetLogisticsList = () => {
  http({
    url: http.adornUrl('/admin/delivery/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    logDataForm.value.dvyNames = data
  })
}

/**
 * 点击保存
 */
const onLogDataFormSubmit = () => {
  let flag = true
  const list = logisticsInfo.value

  list.forEach(el => {
    if (!flag) {
      return false
    }
    if (el.deliveryType === 3 || el.deliveryType === 0) {
      return
    }
    const reg = /^[a-zA-Z0-9]{4,30}$/
    if (el.dvyFlowId.length === 0) {
      ElMessage({
        message: $t('order.logEmpty'),
        type: 'warning'
      })
      flag = false
      errorNum.value = 1
      confirmList.value = []
    } else if (!reg.test(el.dvyFlowId)) {
      ElMessage({
        message: $t('order.checkDvyId'),
        type: 'warning'
      })
      flag = false
      errorNum.value = 1
      confirmList.value = []
    } else {
      errorNum.value = 0
      const list = confirmList.value
      if (
        (el.newDvyFlowId.length !== 0 && el.newDvyFlowId !== el.dvyFlowId) ||
        el.newDvyId !== el.dvyId
      ) {
        list.push(el)
        list.forEach(el => {
          el.delMethod = $t('order.logistics')
          // el.packageName = "包裹" + Number(index+1)
          logDataForm.value.dvyNames.forEach(dvyName => {
            if (el.dvyId === dvyName.dvyId) {
              el.dvyName = dvyName.dvyName
            }
          })
        })
        confirmList.value = list
      }
    }
  })
  if (errorNum.value === 1) {
    return
  } else if (confirmList.value.length === 0) {
    ElMessage({
      message: $t('order.noLogIsChanged'),
      type: 'warning'
    })
    flag = false
  }
  if (flag) {
    isReviseLog.value = false // 修改弹窗
  }
}
/**
 * 确认修改物流信息
 */
const onConfirmRevise = () => {
  http({
    url: http.adornUrl('/order/delivery/updateOrderDeliveries'),
    method: 'put',
    data: http.adornData({
      deliveryOrders: confirmList.value
    }),
    params: http.adornParams()
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success'
    })
    isReviseLog.value = true
    logVisible.value = false
  })
}
/**
 * 返回修改（物流信息）
 */
const onBackToRevise = () => {
  isReviseLog.value = true
  // 修改弹窗
  confirmList.value = [] // 清空确认列表
}

/**
 * 获取数据列表
 */
const dataForm = ref({})
let tempSearchForm = null // 保存上次点击查询的请求条件
const dateRange = ref([])
const defaultTime = ref([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])
const dataList = ref([])
const dataListLoading = ref(false)
const onGetDataList = (pageParam, params, newData = false) => {
  const par = Object.assign(
    {
      orderNumber: dataForm.value.orderNumber,
      orderType: dataForm.value.orderType,
      receiver: dataForm.value.receiver,
      mobile: dataForm.value.mobile,
      status: status.value,
      dvyType: dataForm.value.dvyType,
      payType: dataForm.value.payType,
      stationName: dataForm.value.stationName,
      refundStatus: dataForm.value.refundStatus,
      startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
      endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
    },
    params
  )
  dataForm.value = par
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(par))
  } else {
    tempSearchForm.status = status.value
  }
  pageParam = pageParam ? page.value : pageParam
  dataListLoading.value = true
  http({
    url: http.adornUrl('/order/order/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.value.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.value.pageSize : pageParam.pageSize
        },
        tempSearchForm
      ),
      false
    )
  }).then(({ data }) => {
    dataList.value = data.records
    onHandleDataList()
    page.value.total = data.total
    sts.value = !status.value ? 0 : +status.value
    dataListLoading.value = false
  })
}

const onHandleDataList = () => {
  dataList.value.forEach(order => {
    let isOnlineDelivery = 1
    for (let i = 0; i < order.orderItems.length; i++) {
      if (order.orderItems[i].dvyType === 1) {
        isOnlineDelivery = 0
        break
      }
    }
    order.isOnlineDelivery = isOnlineDelivery
  })
}
// 每页数
const onPageSizeChange = val => {
  page.value.pageSize = val
  page.value.currentPage = 1
  onGetDataList(page.value, {})
}
// 当前页
const onPageChange = val => {
  page.value.currentPage = val
  onGetDataList(page.value, {})
}

/**
 * 导航选择状态
 */
const onSelectNav = e => {
  page.value.currentPage = 1
  const eventSts = e.currentTarget.dataset.sts
  sts.value = parseInt(eventSts)
  status.value = sts.value === 0 ? null : parseInt(eventSts)
  onGetDataList(page.value)
}
const orderStatus = val => {
  status.value = val
}
/**
 * 根据选项设置时间
 * 1:今天 2:昨天 3: 近七天 4:近30天 5:近60天
 */
const onSetDateRange = val => {
  let startDay = null
  let endDay = null
  if (val === 1) {
    startDay = 0
    endDay = 0
  } else if (val === 2) {
    startDay = -1
    endDay = -1
  } else if (val === 3) {
    startDay = -7
    endDay = -1
  } else if (val === 4) {
    startDay = -30
    endDay = -1
  } else {
    return
  }

  // 开始时间
  const startTime = moment().add(startDay, 'days').startOf('days').format('LL')
  // 结束时间
  const endTime = moment().add(endDay, 'days').endOf('days').format('LL')
  dateRange.value = [startTime, endTime]
}
// 新增 / 修改
const addOrUpdateRef = ref(null)
const addOrUpdateVisible = ref(false)
const onAddOrUpdate = val => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(val)
  })
}
// // 退款路由跳转
const onRefundRoute = val => {
  const routeList = store.routeList
  const flag = routeList.some(item => item.url === 'order/order-manage/refund/index')
  if (!flag) {
    ElMessage({
      message: '您暂时没有权限访问',
      type: 'error',
      duration: 1500
    })
    return
  }
  router.push({
    path: '/order/order-manage/refund/index',
    query: { orderNumber: val }
  })
}

// // 清空按钮
const onResetSearch = () => {
  dataForm.value = {}
  dateRange.value = []
  status.value = null
}
// // 搜索查询
const onSearch = (newData = false) => {
  page.value.currentPage = 1
  onGetDataList(page.value, null, newData)
}
/**
 * 更改订单金额
 */
const orderAmountUpdateRef = ref(null)
const orderAmountUpdateVisible = ref(false)
const onEditAmount = order => {
  orderAmountUpdateVisible.value = true
  nextTick(() => {
    orderAmountUpdateRef.value?.init(order)
  })
}
/**
 * 发货
 */
const devyVisible = ref(false)

const orderDeliveryUpdateRef = ref(null)
const onChangeOrder = order => {
  devyVisible.value = true
  nextTick(() => {
    orderDeliveryUpdateRef.value?.init(order)
  })
}
/**
 * 提货
 */
const orderStationRef = ref(null)
const orderStationVisible = ref(false)
const onStationOrder = order => {
  orderStationVisible.value = true
  nextTick(() => {
    orderStationRef.value?.init(order)
  })
}
const onGetWaitingConsignmentExcel = () => {
  onGetDataList(page.value)
}
// 修改金额
const onMountUpdate = () => {
  ElMessage({
    message: $t('order.modifyTheAmount') + ' ' + $t('order.success'),
    type: 'success',
    duration: 1500,
    onClose: () => {
      onGetDataList()
    }
  })
}
const spuUploadRef = ref(null)
const uploadVisible = ref(false)
const onUploadSpu = () => {
  dataForm.value.startTime = dateRange.value === null ? null : dateRange.value[0]
  dataForm.value.endTime = dateRange.value === null ? null : dateRange.value[1]
  uploadVisible.value = true
  nextTick(() => {
    spuUploadRef.value?.init()
  })
}
const onGetSoldExcel = () => {
  if (!dateRange.value || dateRange.value.length < 2) {
    ElMessage.error($t('order.pleExpOrderFirst'))
    return
  }
  ElMessageBox.confirm(`${$t('order.exportReport')}`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/order/order/soldExcel'),
      method: 'get',
      params: http.adornParams({
        orderNumber: dataForm.value.orderNumber,
        orderType: dataForm.value.orderType,
        receiver: dataForm.value.receiver,
        mobile: dataForm.value.mobile,
        status: status.value,
        dvyType: dataForm.value.dvyType,
        payType: dataForm.value.payType,
        stationName: dataForm.value.stationName,
        refundStatus: dataForm.value.refundStatus,
        startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
        endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
      }),
      responseType: 'blob' // 解决文件下载乱码问题
    }).then(({ data }) => {
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
      })
      const fileName = $t('order.orderInfCollationXls')
      const elink = document.createElement('a')
      if ('download' in elink) {
        // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    })
  })
}
// 前往消息盒子
const onToImbox = order => {
  if (order.userWriteOff) {
    ElMessage({
      message: $t('order.userlogoutTips'),
      type: 'error'
    })
    return
  }
  window.open(
    '/message-box/index?userId=' +
      order.userId +
      '&orderNumber=' +
      order.orderNumber,
    'view_window'
  )
}
onUnmounted(() => {
  // 页面销毁时移除监听
  window.removeEventListener('scroll', scrollToTop)
})

/**
 * 预售时间显示为 ’YYYY-MM-DD‘
 */
const preSellTimeShowHandler = (val) => {
  if (!val) return val
  return val.slice(0, -8).trim()
}
</script>
<style scoped lang="scss">
@use './index.scss';

</style>
